package com.atguigu.gmall.search.listener;

import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.common.consts.GmallConsts;
import com.atguigu.gmall.pms.entity.*;
import com.atguigu.gmall.search.feign.GmallPmsClient;
import com.atguigu.gmall.search.feign.GmallWmsClient;
import com.atguigu.gmall.search.vo.Goods;
import com.atguigu.gmall.search.vo.SearchAttrVo;
import com.atguigu.gmall.wms.entity.WareSkuEntity;
import com.rabbitmq.client.Channel;
import io.jsonwebtoken.lang.Collections;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Configuration
public class MqListener {
    //编写消费者消费消息
    @RabbitListener(queues = GmallConsts.SAVE_SPU_QUEUE_NAME)
    // spu保存成功后发送的消息是Long spuid
    public void saveSpuCounsumer(Long spuId , Message message , Channel channel){
        try {
            System.out.println("接收到："+  spuId);
            //使用spuid查询es需要的商品数据 导入到es中
            this.importSpu2Es(spuId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag() , false);
        } catch (Exception e) {
//            e.printStackTrace();
            try {
                if(message.getMessageProperties().isRedelivered()){
                    channel.basicReject(message.getMessageProperties().getDeliveryTag() , false);
                }else{
                    channel.basicNack(message.getMessageProperties().getDeliveryTag() , false,true);
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }

    @Autowired
    ElasticsearchRestTemplate restTemplate;
    @Autowired
    GmallPmsClient pmsClient;
    @Autowired
    GmallWmsClient wmsClient;
    public void importSpu2Es(Long spuId){
        //1、根据spuId查询spuEntity对象
        ResponseVo<SpuEntity> spuEntityResponseVo = pmsClient.querySpuById(spuId);
        SpuEntity spuEntity = spuEntityResponseVo.getData();
        if(spuEntity==null){
            return;
        }
        //2.1 根据spu中的brandId查询品牌
        Long brandId = spuEntity.getBrandId();
        ResponseVo<BrandEntity> brandEntityResponseVo = pmsClient.queryBrandById(brandId);
        BrandEntity brandEntity = brandEntityResponseVo.getData();
        //2.2 根据spu的categoryId查询分类
        ResponseVo<CategoryEntity> categoryEntityResponseVo = pmsClient.queryCategoryById(spuEntity.getCategoryId());
        CategoryEntity categoryEntity = categoryEntityResponseVo.getData();
        //2.3 根据spu的id查询它的检索属性和值
        ResponseVo<List<SpuAttrValueEntity>> spuAttreValuesResponseVo = pmsClient.querySpuAttreValuesBySpuId(spuId);
        List<SpuAttrValueEntity> spuAttrValueEntities = spuAttreValuesResponseVo.getData();

        //2.4 根据spu查询它的sku列表
        ResponseVo<List<SkuEntity>> skusResponseVo = pmsClient.querySkusBySpuId(spuId);
        List<SkuEntity> skuEntities = skusResponseVo.getData();
        //3、遍历sku
        if(Collections.isEmpty(skuEntities)){
            return;//没有sku时 不能创建goods对象 直接结束
        }
        List<Goods> goodsList = new ArrayList<>();
        skuEntities.forEach(skuEntity -> {
            Long skuId = skuEntity.getId();
            //3.1 根据sku的id查询它的检索属性和值
            ResponseVo<List<SkuAttrValueEntity>> skuAttrValuesResponseVo = pmsClient.querySkuAttrValuesBySkuId(skuId);
            List<SkuAttrValueEntity> skuAttrValueEntities = skuAttrValuesResponseVo.getData();
            //3.2 根据sku的id查询wms中它的库存和销量数据
            ResponseVo<List<WareSkuEntity>> wareSkusResponseVo = wmsClient.queryWareSkuBySkuId(skuId);
            List<WareSkuEntity> wareSkuEntities = wareSkusResponseVo.getData();
            //创建Goods对象：将上面查询到的一个sku的数据设置给他   添加到goods集合中

            Goods goods = new Goods();
            goods.setSkuId(skuId);
            goods.setTitle(skuEntity.getTitle());
            goods.setSubtitle(skuEntity.getSubtitle());
            goods.setDefaultImage(skuEntity.getDefaultImage());
            goods.setPrice(skuEntity.getPrice().doubleValue());
            goods.setCreateTime(spuEntity.getCreateTime());
            if(categoryEntity!=null){
                goods.setCategoryName(categoryEntity.getName());
                goods.setCategoryId(categoryEntity.getId());
            }
            if(brandEntity!=null){
                goods.setBrandId(Long.parseLong(brandEntity.getId()));
                goods.setBrandName(brandEntity.getName());
                goods.setLogo(brandEntity.getLogo());
            }

//                    List<SearchAttrVo> searchAttrVos = new ArrayList<>();
            //goods的检索属性   包含了spu的和sku的 attrValues
            if(!Collections.isEmpty(spuAttrValueEntities)){
                spuAttrValueEntities.forEach(spuAttrValueEntity -> {
                    //将spuAttrValueEntity转为一个SearchAttrVo对象
                    SearchAttrVo searchAttrVo = new SearchAttrVo();
                    searchAttrVo.setAttrId(spuAttrValueEntity.getAttrId());
                    searchAttrVo.setAttrValue(spuAttrValueEntity.getAttrValue());
                    searchAttrVo.setAttrName(spuAttrValueEntity.getAttrName());
                    goods.getSearchAttrs().add(searchAttrVo);
                });
            }
            if(!Collections.isEmpty(skuAttrValueEntities)){
                skuAttrValueEntities.forEach(skuAttrValueEntity -> {
                    SearchAttrVo searchAttrVo = new SearchAttrVo();
                    searchAttrVo.setAttrId(skuAttrValueEntity.getAttrId());
                    searchAttrVo.setAttrValue(skuAttrValueEntity.getAttrValue());
                    searchAttrVo.setAttrName(skuAttrValueEntity.getAttrName());
                    goods.getSearchAttrs().add(searchAttrVo);
                });
            }
//                    goods.setSearchAttrs(searchAttrVos);
            //销量和库存时wmssku表中的数据：
            //是否有库存：每个sku有多个仓库的数据
//                    wareSkuEntities 一个sku的多个仓库 任何一个有库存  store设置为true、
            if(!Collections.isEmpty(wareSkuEntities)){
                boolean store = wareSkuEntities.stream()
                        .anyMatch(wareSkuEntity -> wareSkuEntity.getStock() - wareSkuEntity.getStockLocked() > 0);
                goods.setStore(store);
                // 一个sku的多个仓库数据  所有的仓库的销量累加得到的就是商品的总销量
                Long sales = wareSkuEntities.stream()
                        .map(WareSkuEntity::getSales).reduce((sale1, sale2) -> sale1 + sale2).get();
                goods.setSales(sales);
            }
            //将goods存到goodsList中
            goodsList.add(goods);
        });
        //将goodsList导入到es中
        restTemplate.save(goodsList);
    }
}
